package net.chenlin.dp.common.interceprot;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * Created by lance
 * on 2018/2/11.
 */
public class RequestInfoInter extends HandlerInterceptorAdapter {
    Logger log = LoggerFactory.getLogger(RequestInfoInter.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String UA =  request.getHeader("user-agent");
        log.info("UA :" + UA);
        StringBuffer buffer = new StringBuffer("");
        Enumeration<String> enume = request.getParameterNames();
        // 二进制表单不处理

        if(MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(request.getHeader(HttpHeaders.CONTENT_TYPE))){
            //为空，直接返回
            String json = IOUtils.toString(request.getInputStream(), "utf-8");
            if (StringUtils.isNotBlank(json)) {
                log.info("request info :" + json);
            }
        }
        while (enume.hasMoreElements()) {
            String key = enume.nextElement();
            String[] value = request.getParameterValues(key);
            if (buffer.toString().length() > 0) {
                buffer.append("  ");
            }
            buffer.append(key).append("=").append(Arrays.toString(value));
        }
        log.debug("request form info " + buffer.toString() );
        return super.preHandle(request, response, handler);
    }
}
